<?php
namespace App\HttpController\Pudu;

use App\Common\Controller\Rest;

class Settle extends Rest
{
    public $modelName = 'Shop'; // model 类名称

    /**
     * 创建结算
     *
     * @return void
     */
    public function POSTIndex()
    {
        // DONE 系统检查
        $rules = [
            'totalMoney' => 'require|number|gt:0',
        ];
        $message = [
            'totalMoney.require' => '总结算金额不能为空',
            'totalMoney.number'  => '总结算金额必须为数字',
            'totalMoney.require' => '总结算金额必须大于0',
        ];
        $this->validate($this->param, $rules, $message);

        // 执行返现
        $toatalMoney = $this->param['totalMoney'];

        $configs = $this->configs();

        $rules = [
            'RESERVE_LEVEL_1' => 'require|number|gt:0',
            'RESERVE_LEVEL_2' => 'require|number|gt:0',
            'RESERVE_LEVEL_3' => 'require|number|gt:0',
            'RESERVE_LEVEL_4' => 'require|number|gt:0',
            'RESERVE_LEVEL_5' => 'require|number|gt:0',
            'RESERVE_LEVEL_6' => 'require|number|gt:0',
            'RESERVE_LEVEL_7' => 'require|number|gt:0',
        ];
        $this->validate($configs, $rules);
        // DONE 进行分红

        // DONE 读取所有的董事 遍历董事  根据董事级别执行返现
        $Member = $this->model('Member');
        $users = $Member->where(['status' => 1])->where('level', '>', 0)->select()->toArray();
        $word = [1, 2, 3, 4, 5, 6, 7];
        $count = array_count_values(array_column($users, "level"));

        $wordCount = [];
        foreach ($word as $k => $v) {
            $sl = isset($count[$v]) ? $count[$v] : 0;
            $wordCount[] = [
                'count' => $sl,
            ];
        }

        for ($i = 1; $i <= 7; $i++) {
            $name = 'countLevel' . $i;
            $$name = array_sum(array_map(create_function('$val', 'return $val["count"];'), $wordCount));
            array_shift($wordCount);
        }

        // DONE 获取各个级别应得的利润
        for ($k = 1; $k <= 7; $k++) {
            $name = 'countLevel' . $k;

            // 某个级别没有董事
            if ($$name == 0) {
                continue;
            }

            $configName = 'RESERVE_LEVEL_' . $k;
            $shareName = 'share' . $k;
            $$shareName = $toatalMoney * $configs[$configName] / 100 / $$name;
            if($k != 1){
                $tmpName = 'share' . ($k - 1);
                $$shareName += $$tmpName;
            }
        }
        $Member->startTrans();
        try {
            foreach ($users as $k => $v) {
                $shareName = 'share' . $v['level'];
                $Member->where(['id' => $v['id']])->setInc('share', $$shareName);
                $record[] = [
                    'userId' => $v['id'],
                    'username' => $v['username'],
                    'change' => $$shareName,
                    'remain' => $v['share']+$$shareName,
                    'type' => 4,
                    'remark' => '董事分红',
                ];
            }
            if (isset($record)) {
                $this->model('MemberRecord')->insertAll($record);
            }
            $Member->commit();
        } catch (\Exception $e) {
            $Member->rollbakc();
            $this->error(['msg' => $e->getMessage()]);
        }
        $this->result();
    }

    /**
     * 读取并缓存系统配置
     */
    private function configs()
    {
        $systemConfig = \think\Cache::get('PUDU_CONFIG_DATA');
        if (!$systemConfig) {
            //获取所有系统配置
            $model = $this->model('PuduConfig');
            $systemConfig = $model->getDataOfList();
            // 检查是否抛出异常
            $this->abort($systemConfig, '应用配置获取失败');
            \think\Cache::set('PUDU_CONFIG_DATA', null);
            \think\Cache::set('PUDU_CONFIG_DATA', $systemConfig, 36000); //缓存配置
        }
        return $systemConfig;
    }

    /**
     * 转移
     *
     * @return void
     */
    public function GETIndex()
    {
        // 查询出所有有董事红包余额的用户
        $Member = $this->model('Member');
        $users = $Member->where('share', '>', 0)->select();
        foreach ($users as $k => $v) {
            $record[] = [
                'userId' => $v['id'],
                'username' => $v['username'],
                'change' => -$v['share'],
                'remain' => 0,
                'type' => 4,
                'remark' => '系统转出到账户余额',
            ];
            $record[] = [
                'userId' => $v['id'],
                'username' => $v['username'],
                'change' => $v['share'],
                'remain' => $v['share'] + $v['balance'],
                'type' => 1,
                'remark' => '董事红包转入',
            ];
        }
        $Member->startTrans();
        try {
            if (isset($record)) {
                $this->model('MemberRecord')->insertAll($record);
            }
            $Member->query('UPDATE pudu_members SET balance = balance + share, share = 0');
            $Member->commit();
        } catch (\Exception $e) {
            $Member->rollback();
            $this->error(['msg' => $e->getMessage()]);
        }
        $this->result();
    }
}
